// axios 基础配置
import axios from "axios";
import router from "@/router";
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import { useUserStore } from "@/stores/useUserStore";

// 创建axios实例
const http = axios.create({
  baseURL: "/api",
  timeout: 5000,
});
// axios请求拦截器
http.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    return config;
  },
  e => Promise.reject(e)
);

// axios响应式拦截器
http.interceptors.response.use(
  res => res.data,
  e => {
    if (e.response.status === 401) {
      ElMessage({ type: "error", message: "登录已过期，请重新登录" });
      localStorage.clear("token");
      router.replace("/login");
    } else {
      ElMessage({ type: "error", message: e.message });
    }
    return Promise.reject(e);
  }
);

export default http;
